<?php
/**
 * Created by PhpStorm.
 * User: zjw
 * Date: 2018/3/29
 * Time: 上午11:40
 */

namespace backend\models;

use common\models\Coupon;
use yii\data\ActiveDataProvider;
use yii\db\ActiveQuery;

/**
 *
 * @property ActiveQuery $query
 */
class CouponSearch extends Coupon
{
    public $status;
    public $catalog_mark_id;
    public $startTime;
    public $endTime;
    public $query;

    public function rules()
    {
        return [
            [['status'], 'integer'],
            [['startTime', 'endTime','catalog_mark_id'], 'string']
        ];
    }

    public function search($params)
    {
        $this->query = Coupon::find();
        $dataProvider = new ActiveDataProvider([
            'query' => $this->query
        ]);
        if (!$this->load($params)) {
            return $dataProvider;
        }
        if (isset($this->status) && is_numeric($this->status)) {
            $this->setStatus();
        }

        if (isset($this->startTime) && $this->startTime !== '') {
            $this->setStartTime();
        }

        if (isset($this->endTime) && $this->endTime !== '') {
            $this->setEndTime();
        }

        if (isset($this->catalog_mark_id) && $this->catalog_mark_id !== '') {
            $this->setCatalog();
        }

        return $dataProvider;
    }

    private function setStatus()
    {
        $this->query->andWhere(['status' => $this->status]);
    }

    private function setStartTime()
    {
        $this->query->andWhere(['>', 'updated_at', strtotime($this->startTime . " 00:00:00")]);
    }

    private function setEndTime()
    {
        $this->query->andWhere(['<', 'updated_at', strtotime($this->endTime . " 23:59:59")]);
    }

    private function setCatalog()
    {
        $this->query->andWhere(['catalog_mark_id' => $this->catalog_mark_id]);
    }
}
